<template>
  <div class="animal-manage-page">
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Files /></el-icon>
            <span class="header-title">动物管理</span>
          </div>
          <el-button type="primary" @click="openDialog()" :icon="Plus">
            新增动物
          </el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索动物名称"
          clearable
          style="max-width: 300px;"
          @clear="handleSearch"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-select
          v-model="filterSpecies"
          placeholder="选择种类"
          clearable
          style="width: 150px;"
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option label="狗" value="狗" />
          <el-option label="猫" value="猫" />
          <el-option label="其他" value="其他" />
        </el-select>
        <el-select
          v-model="filterStatus"
          placeholder="选择状态"
          clearable
          style="width: 150px;"
          @change="handleSearch"
        >
          <el-option label="全部" value="" />
          <el-option label="待领养" :value="0" />
          <el-option label="已领养" :value="1" />
          <el-option label="审核中" :value="2" />
        </el-select>
        <el-button @click="handleReset" :icon="Refresh">重置</el-button>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="filteredList" 
        border 
        stripe
        v-loading="loading"
        style="width: 100%; margin-top: 20px;"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: '600' }"
        :row-style="{ height: '70px' }"
        table-layout="auto"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="photo" label="图片" width="110" align="center">
          <template #default="{ row }">
            <div 
              v-if="row.photo"
              class="image-preview-cell"
              @click="previewAnimalImage(row)"
            >
              <el-image
                :src="formatImageUrl(row.photo)"
                fit="cover"
                style="width: 65px; height: 65px; border-radius: 8px; cursor: pointer; border: 2px solid #e4e7ed;"
              />
            </div>
            <div v-else class="no-image-box">
              <el-icon :size="24"><Picture /></el-icon>
              <span>暂无</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="昵称" min-width="120" />
        <el-table-column prop="species" label="种类" width="100" align="center" />
        <el-table-column prop="breed" label="品种" width="120" align="center">
          <template #default="{ row }">
            {{ row.breed || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80" align="center" />
        <el-table-column prop="age" label="年龄" width="100" align="center" />
        <el-table-column prop="color" label="毛色" width="100" align="center" />
        <el-table-column prop="location" label="位置" min-width="150" show-overflow-tooltip>
          <template #default="{ row }">
            {{ row.location || '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ statusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rescueTime" label="救助时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.rescueTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            <span :title="row.description">{{ row.description || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center" fixed="right">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="openDialog(row)"
              :icon="Edit"
            >
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="success"
              @click="openHealthDialog(row)"
              :icon="DocumentChecked"
            >
              健康档案
            </el-button>
            <el-button 
              size="small" 
              type="warning"
              @click="openStoryDialog(row)"
              :icon="Document"
            >
              故事档案
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="del(row.id)"
              :icon="Delete"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <el-empty 
        v-if="!loading && list.length === 0" 
        description="暂无数据"
        style="margin: 40px 0;"
      />

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 编辑弹窗 -->
    <el-dialog 
      v-model="visible" 
      :title="form.id ? '编辑动物' : '新增动物'" 
      width="700px"
      @close="handleDialogClose"
    >
      <el-form 
        ref="formRef"
        :model="form" 
        :rules="formRules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="昵称" prop="name">
              <el-input v-model="form.name" placeholder="请输入动物昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="种类" prop="species">
              <el-input v-model="form.species" placeholder="请输入种类" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品种" prop="breed">
              <el-input v-model="form.breed" placeholder="请输入品种" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%;">
                <el-option label="公" value="公" />
                <el-option label="母" value="母" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input v-model="form.age" placeholder="请输入年龄" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="毛色" prop="color">
              <el-input v-model="form.color" placeholder="请输入毛色" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 200px;">
            <el-option label="待领养" :value="0" />
            <el-option label="已领养" :value="1" />
            <el-option label="审核中" :value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="位置">
          <el-input v-model="form.location" placeholder="请输入位置信息" />
        </el-form-item>

        <el-form-item label="救助时间">
          <el-date-picker
            v-model="form.rescueTime"
            type="datetime"
            placeholder="选择救助时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="图片">
          <el-upload
            action="http://localhost:8080/api/admin/animal/upload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :show-file-list="false"
            accept="image/*"
          >
            <template #trigger>
              <div class="upload-area">
                <img 
                  v-if="form.photo" 
                  :src="formatImageUrl(form.photo)" 
                  class="upload-image"
                />
                <div v-else class="upload-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">点击上传</div>
                </div>
              </div>
            </template>
          </el-upload>
          <div class="upload-tip">支持 jpg/png 格式，建议尺寸 600x600</div>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="form.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入动物描述信息"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="visible = false">取消</el-button>
          <el-button type="primary" @click="save" :loading="saving">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 健康档案抽屉 -->
    <el-drawer
      v-model="healthDrawerVisible"
      title="健康档案管理"
      :size="800"
      :before-close="handleHealthDrawerClose"
    >
      <template #header>
        <div style="display: flex; align-items: center; gap: 8px;">
          <el-icon><DocumentChecked /></el-icon>
          <span>{{ currentAnimal?.name }} - 健康档案</span>
        </div>
      </template>

      <div class="drawer-content">
        <div class="drawer-header">
          <el-button type="primary" @click="openHealthFormDialog()" :icon="Plus">
            新增健康记录
          </el-button>
        </div>

        <el-table 
          :data="healthList" 
          border 
          stripe
          v-loading="healthLoading"
          style="margin-top: 20px;"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="checkDate" label="检查日期" width="150" align="center">
            <template #default="{ row }">
              {{ formatDate(row.checkDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="disease" label="疾病记录" min-width="180" show-overflow-tooltip />
          <el-table-column prop="vaccine" label="疫苗接种" min-width="180" show-overflow-tooltip />
          <el-table-column prop="notes" label="备注" min-width="200" show-overflow-tooltip />
          <el-table-column label="操作" width="150" align="center">
            <template #default="{ row }">
              <el-button 
                size="small" 
                @click="openHealthFormDialog(row)"
                :icon="Edit"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="delHealth(row.id)"
                :icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-empty 
          v-if="!healthLoading && healthList.length === 0" 
          description="暂无健康档案记录"
          style="margin: 40px 0;"
        />
      </div>
    </el-drawer>

    <!-- 健康档案表单对话框 -->
    <el-dialog 
      v-model="healthFormVisible" 
      :title="healthForm.id ? '编辑健康档案' : '新增健康档案'" 
      width="700px"
      @close="handleHealthFormClose"
    >
      <el-form 
        ref="healthFormRef"
        :model="healthForm" 
        :rules="healthFormRules"
        label-width="100px"
      >
        <el-form-item label="检查日期" prop="checkDate">
          <el-date-picker
            v-model="healthForm.checkDate"
            type="date"
            placeholder="选择检查日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%;"
          />
        </el-form-item>

        <el-form-item label="疾病记录">
          <el-input 
            v-model="healthForm.disease" 
            type="textarea"
            :rows="3"
            placeholder="请输入疾病记录，如无疾病请填写'健康'"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="疫苗接种">
          <el-input 
            v-model="healthForm.vaccine" 
            type="textarea"
            :rows="3"
            placeholder="请输入疫苗接种记录，如已接种的疫苗类型和时间"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input 
            v-model="healthForm.notes" 
            type="textarea"
            :rows="4"
            placeholder="请输入其他备注信息"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="healthFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveHealth" :loading="healthSaving">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 故事档案抽屉 -->
    <el-drawer
      v-model="storyDrawerVisible"
      title="故事档案管理"
      :size="900"
      :before-close="handleStoryDrawerClose"
    >
      <template #header>
        <div style="display: flex; align-items: center; gap: 8px;">
          <el-icon><Document /></el-icon>
          <span>{{ currentAnimal?.name }} - 故事档案</span>
        </div>
      </template>

      <div class="drawer-content">
        <div class="drawer-header">
          <el-button type="primary" @click="openStoryFormDialog()" :icon="Plus">
            新增故事
          </el-button>
        </div>
  
        <el-table 
          :data="storyList" 
          border 
          stripe
          v-loading="storyLoading"
          style="margin-top: 20px;"
        >
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column prop="photo" label="图片" width="120" align="center">
            <template #default="{ row }">
              <div 
                v-if="row.photo"
                class="image-preview-cell"
                @click="previewStoryImage(row)"
              >
                <el-image
                  :src="formatImageUrl(row.photo)"
                  fit="cover"
                  style="width: 80px; height: 80px; border-radius: 6px; cursor: pointer;"
                />
              </div>
              <span v-else class="no-image">暂无图片</span>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="content" label="内容" min-width="300" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" width="180" align="center">
            <template #default="{ row }">
              {{ formatTime(row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="center">
            <template #default="{ row }">
              <el-button 
                size="small" 
                @click="openStoryFormDialog(row)"
                :icon="Edit"
              >
                编辑
              </el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="delStory(row.id)"
                :icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-empty 
          v-if="!storyLoading && storyList.length === 0" 
          description="暂无故事记录"
          style="margin: 40px 0;"
        />
      </div>
    </el-drawer>

    <!-- 故事表单对话框 -->
    <el-dialog 
      v-model="storyFormVisible" 
      :title="storyForm.id ? '编辑故事' : '新增故事'" 
      width="800px"
      @close="handleStoryFormClose"
    >
      <el-form 
        ref="storyFormRef"
        :model="storyForm" 
        :rules="storyFormRules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="storyForm.title" 
            placeholder="请输入故事标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input 
            v-model="storyForm.content" 
            type="textarea" 
            :rows="8"
            placeholder="请输入救助故事内容"
            maxlength="2000"
            show-word-limit
          />
          </el-form-item>

          <el-form-item label="图片">
            <el-upload
            action="http://localhost:8080/api/admin/story/upload"
            :on-success="handleStoryUploadSuccess"
            :on-error="handleStoryUploadError"
            :show-file-list="false"
            accept="image/*"
          >
            <template #trigger>
              <div class="upload-area-small">
                <img 
                  v-if="storyForm.photo" 
                  :src="formatImageUrl(storyForm.photo)" 
                  class="upload-image"
                />
                <div v-else class="upload-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">点击上传</div>
                </div>
              </div>
            </template>
            </el-upload>
          <div class="upload-tip">支持 jpg/png 格式，建议尺寸 800x600</div>
          </el-form-item>
        </el-form>

        <template #footer>
        <div class="dialog-footer">
          <el-button @click="storyFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveStory" :loading="storySaving">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog 
      v-model="imagePreviewVisible" 
      title="图片预览" 
      width="90%"
      class="preview-dialog"
      @closed="handleImagePreviewClosed"
    >
      <div class="preview-container">
        <div class="preview-wrapper">
          <img 
            :src="previewImageUrl" 
            class="preview-image-full"
            alt="预览图片"
          />
        </div>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script setup>
import { ref, onMounted, computed } from "vue";
  import { ElMessage, ElMessageBox } from "element-plus";
import { Files, Plus, Search, Refresh, Edit, Delete, DocumentChecked, Document, Picture, ZoomIn, ZoomOut } from '@element-plus/icons-vue';
  import axios from "axios";
  
  const list = ref([]);
  const visible = ref(false);
const searchKeyword = ref("");
const filterStatus = ref("");
const filterSpecies = ref("");
const loading = ref(false);
const saving = ref(false);
  const form = ref({});
const formRef = ref(null);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 健康档案相关
const healthDrawerVisible = ref(false);
const healthFormVisible = ref(false);
const healthList = ref([]);
const healthLoading = ref(false);
const healthSaving = ref(false);
const healthForm = ref({});
const healthFormRef = ref(null);
const currentAnimal = ref(null);

// 故事档案相关
const storyDrawerVisible = ref(false);
const storyFormVisible = ref(false);
const storyList = ref([]);
const storyLoading = ref(false);
const storySaving = ref(false);
const storyForm = ref({});
const storyFormRef = ref(null);

// 图片预览相关
const imagePreviewVisible = ref(false);
const previewImageUrl = ref('');

const formRules = {
  name: [{ required: true, message: '请输入动物昵称', trigger: 'blur' }],
  species: [{ required: true, message: '请输入种类', trigger: 'blur' }],
  breed: [{ required: true, message: '请输入品种', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  color: [{ required: true, message: '请输入毛色', trigger: 'blur' }]
};

const healthFormRules = {
  checkDate: [{ required: true, message: '请选择检查日期', trigger: 'change' }]
};

const storyFormRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
};

const statusText = (s) => s === 0 ? "待领养" : s === 1 ? "已领养" : "审核中";

const getStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'success',
    2: 'warning'
  };
  return typeMap[status] || 'info';
};

// 不再需要前端过滤，后端已经处理
const filteredList = computed(() => list.value);

const formatImageUrl = (url) => {
  if (!url) return '';
  if (url.startsWith('http')) return url;
  if (url.startsWith('/')) return `http://localhost:8080${url}`;
  return `http://localhost:8080/uploads/${url}`;
};

const formatDate = (date) => {
  if (!date) return '-';
  return date;
};

const formatTime = (time) => {
  if (!time) return '-';
  return time;
};

const formatDateTime = (datetime) => {
  if (!datetime) return '-';
  // 处理 ISO 格式日期时间
  if (datetime.includes('T')) {
    return datetime.replace('T', ' ').substring(0, 19);
  }
  return datetime;
};
  
  const getList = async () => {
  loading.value = true;
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    };
    
    if (searchKeyword.value) {
      params.name = searchKeyword.value;
    }
    if (filterStatus.value !== '') {
      params.status = filterStatus.value;
    }
    if (filterSpecies.value) {
      params.species = filterSpecies.value;
    }
    
    const res = await axios.get("http://localhost:8080/api/admin/animal/list", { 
      params 
    });
    if (res.data.code === 200) {
    list.value = res.data.data || [];
      total.value = res.data.total || 0;
    } else {
      ElMessage.error(res.data.msg || '获取数据失败');
    }
  } catch (error) {
    console.error('获取动物列表失败:', error);
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
  };
  
  const openDialog = (row) => {
  if (row) {
    form.value = { ...row };
    // 处理图片URL
    if (form.value.photo && !form.value.photo.startsWith('http')) {
      form.value.photo = formatImageUrl(form.value.photo);
    }
    // 处理救助时间：如果是 ISO 格式，转换为日期选择器需要的格式
    if (form.value.rescueTime && form.value.rescueTime.includes('T')) {
      // 后端返回的是 ISO 格式 "2025-11-01T10:30:00"，需要保持为 ISO 格式用于提交
      // 日期选择器会自动处理
    }
  } else {
    form.value = {
      name: '',
      species: '',
      breed: '',
      gender: '',
      age: '',
      color: '',
      status: 0,
      photo: '',
      description: '',
      location: '',
      rescueTime: null
    };
  }
    visible.value = true;
  };

const handleDialogClose = () => {
  formRef.value?.resetFields();
  form.value = {};
};
  
  const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    form.value.photo = res.url || res.data?.url || res.data;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(res.msg || '图片上传失败');
  }
};

const handleUploadError = () => {
  ElMessage.error('图片上传失败');
  };
  
  const save = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息');
      return;
    }
    
    saving.value = true;
    try {
      const isUpdate = form.value.id;
      const url = isUpdate
        ? "http://localhost:8080/api/admin/animal/update" 
        : "http://localhost:8080/api/admin/animal/add";
      
      // 准备提交数据，确保 rescueTime 格式正确
      const submitData = { ...form.value };
      
      // 如果 rescueTime 是空字符串，设为 null
      if (submitData.rescueTime === '' || submitData.rescueTime === null || submitData.rescueTime === undefined) {
        submitData.rescueTime = null;
      } else if (submitData.rescueTime && !submitData.rescueTime.includes('T')) {
        // 如果不是 ISO 格式，转换为 ISO 格式（将空格替换为 T）
        submitData.rescueTime = submitData.rescueTime.replace(' ', 'T');
      }
      
      const method = isUpdate ? 'put' : 'post';
      const res = await axios[method](url, submitData);
    if (res.data.code === 200) {
      ElMessage.success("保存成功");
      visible.value = false;
      getList();
      } else {
        ElMessage.error(res.data.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存失败:', error);
      console.error('提交的数据:', submitData);
      ElMessage.error('保存失败：' + (error.response?.data?.msg || error.message || '未知错误'));
    } finally {
      saving.value = false;
    }
  });
  };
  
  const del = async (id) => {
  try {
    await ElMessageBox.confirm("确定删除该动物吗？", "提示", { 
      type: "warning",
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    });
    
    // Spring Boot 期望的格式是 ids=1&ids=2（重复参数名）
    // 使用 axios 的 params 配置，需要正确序列化数组
    const res = await axios.delete("http://localhost:8080/api/admin/animal/delete", {
      params: { ids: [id] },
      paramsSerializer: (params) => {
        // 手动构建查询字符串，支持数组参数
        const parts = [];
        for (const key in params) {
          const value = params[key];
          if (Array.isArray(value)) {
            value.forEach(item => parts.push(`${key}=${encodeURIComponent(item)}`));
          } else {
            parts.push(`${key}=${encodeURIComponent(value)}`);
          }
        }
        return parts.join('&');
      }
    });
    if (res.data.code === 200) {
      ElMessage.success("删除成功");
      // 如果当前页没有数据了，返回上一页
      if (list.value.length === 1 && currentPage.value > 1) {
        currentPage.value--;
      }
      getList();
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

const handleSearch = () => {
  currentPage.value = 1; // 重置到第一页
  getList();
};

const handleReset = () => {
  searchKeyword.value = '';
  filterStatus.value = '';
  filterSpecies.value = '';
  currentPage.value = 1;
  getList();
};

// 分页相关方法
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  getList();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  getList();
};

// 健康档案相关方法
const openHealthDialog = async (row) => {
  currentAnimal.value = row;
  healthDrawerVisible.value = true;
  await loadHealthList(row.id);
};

const loadHealthList = async (animalId) => {
  healthLoading.value = true;
  try {
    const res = await axios.get("http://localhost:8080/api/admin/health/list", { 
      params: { animalId } 
    });
    if (res.data.code === 200) {
      healthList.value = res.data.data || [];
    } else {
      ElMessage.error(res.data.msg || '获取健康档案失败');
    }
  } catch (error) {
    console.error('获取健康档案失败:', error);
    ElMessage.error('获取健康档案失败');
  } finally {
    healthLoading.value = false;
  }
};

const openHealthFormDialog = (row) => {
  if (row) {
    healthForm.value = { ...row };
  } else {
    healthForm.value = {
      animalId: currentAnimal.value.id,
      checkDate: '',
      disease: '',
      vaccine: '',
      notes: ''
    };
  }
  healthFormVisible.value = true;
};

const handleHealthFormClose = () => {
  healthFormRef.value?.resetFields();
  healthForm.value = {};
};

const saveHealth = async () => {
  if (!healthFormRef.value) return;
  
  await healthFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息');
      return;
    }
    
    healthSaving.value = true;
    try {
      const isUpdate = healthForm.value.id;
      const url = isUpdate
        ? "http://localhost:8080/api/admin/health/update" 
        : "http://localhost:8080/api/admin/health/add";
      
      const method = isUpdate ? 'put' : 'post';
      const res = await axios[method](url, healthForm.value);
      if (res.data.code === 200) {
        ElMessage.success("保存成功");
        healthFormVisible.value = false;
        await loadHealthList(currentAnimal.value.id);
      } else {
        ElMessage.error(res.data.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存失败:', error);
      ElMessage.error('保存失败');
    } finally {
      healthSaving.value = false;
    }
  });
};

const delHealth = async (id) => {
  try {
    await ElMessageBox.confirm("确定删除该健康记录吗？", "提示", { 
      type: "warning",
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    });
    
    const res = await axios.delete(`http://localhost:8080/api/admin/health/delete/${id}`);
    if (res.data.code === 200) {
      ElMessage.success("删除成功");
      await loadHealthList(currentAnimal.value.id);
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

const handleHealthDrawerClose = (done) => {
  healthList.value = [];
  healthFormVisible.value = false;
  healthForm.value = {};
  if (healthFormRef.value) {
    healthFormRef.value.resetFields();
  }
  currentAnimal.value = null;
  if (typeof done === 'function') {
    done();
  }
};

// 故事档案相关方法
const openStoryDialog = async (row) => {
  currentAnimal.value = row;
  storyDrawerVisible.value = true;
  await loadStoryList(row.id);
};

const loadStoryList = async (animalId) => {
  storyLoading.value = true;
  try {
    const res = await axios.get("http://localhost:8080/api/admin/story/list", {
      params: { animalId }
    });
    if (res.data.code === 200) {
      storyList.value = res.data.data || [];
    } else {
      ElMessage.error(res.data.msg || '获取故事列表失败');
    }
  } catch (error) {
    console.error('获取故事列表失败:', error);
    ElMessage.error('获取故事列表失败');
  } finally {
    storyLoading.value = false;
  }
};

const openStoryFormDialog = (row) => {
  if (row) {
    storyForm.value = { ...row };
    if (storyForm.value.photo && !storyForm.value.photo.startsWith('http')) {
      storyForm.value.photo = formatImageUrl(storyForm.value.photo);
    }
  } else {
    storyForm.value = {
      animalId: currentAnimal.value.id,
      title: '',
      content: '',
      photo: ''
    };
  }
  storyFormVisible.value = true;
};

const handleStoryFormClose = () => {
  storyFormRef.value?.resetFields();
  storyForm.value = {};
};

const handleStoryUploadSuccess = (res) => {
  if (res.code === 200) {
    storyForm.value.photo = res.url || res.data?.url || res.data;
    ElMessage.success('图片上传成功');
  } else {
    ElMessage.error(res.msg || '图片上传失败');
  }
};

const handleStoryUploadError = () => {
  ElMessage.error('图片上传失败');
};

const saveStory = async () => {
  if (!storyFormRef.value) return;
  
  await storyFormRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息');
      return;
    }
    
    storySaving.value = true;
    try {
      const isUpdate = storyForm.value.id;
      const url = isUpdate
        ? "http://localhost:8080/api/admin/story/update" 
        : "http://localhost:8080/api/admin/story/add";
      
      const method = isUpdate ? 'put' : 'post';
      const res = await axios[method](url, storyForm.value);
      if (res.data.code === 200) {
        ElMessage.success("保存成功");
        storyFormVisible.value = false;
        await loadStoryList(currentAnimal.value.id);
      } else {
        ElMessage.error(res.data.msg || '保存失败');
      }
    } catch (error) {
      console.error('保存失败:', error);
      ElMessage.error('保存失败');
    } finally {
      storySaving.value = false;
    }
  });
};

const delStory = async (id) => {
  try {
    await ElMessageBox.confirm("确定删除该故事吗？", "提示", { 
      type: "warning",
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    });
    
    const res = await axios.delete(`http://localhost:8080/api/admin/story/delete/${id}`);
    if (res.data.code === 200) {
      ElMessage.success("删除成功");
      await loadStoryList(currentAnimal.value.id);
    } else {
      ElMessage.error(res.data.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

const handleStoryDrawerClose = (done) => {
  storyList.value = [];
  storyFormVisible.value = false;
  storyForm.value = {};
  if (storyFormRef.value) {
    storyFormRef.value.resetFields();
  }
  currentAnimal.value = null;
  if (typeof done === 'function') {
    done();
  }
};

// 预览动物图片
const previewAnimalImage = (row) => {
  if (row.photo) {
    previewImageUrl.value = formatImageUrl(row.photo);
    imagePreviewVisible.value = true;
  }
};

// 预览故事图片
const previewStoryImage = (row) => {
  if (row.photo) {
    previewImageUrl.value = formatImageUrl(row.photo);
    imagePreviewVisible.value = true;
  }
};

// 关闭图片预览
const handleImagePreviewClosed = () => {
  previewImageUrl.value = '';
};
  
  onMounted(getList);
  </script>
  
  <style scoped>
.animal-manage-page {
  width: 100%;
}

.main-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 22px;
  color: #409EFF;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.no-image {
  color: #909399;
  font-size: 12px;
}

.no-image-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 4px;
  color: #909399;
  font-size: 12px;
  padding: 8px;
}

.image-preview-cell {
  cursor: pointer;
  display: inline-block;
}

.image-preview-cell:hover {
  opacity: 0.8;
}

.upload-area {
  width: 150px;
  height: 150px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
}

.upload-area:hover {
  border-color: #409EFF;
  background: #f5f7fa;
}

.upload-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.upload-icon {
  font-size: 32px;
  color: #8c939d;
}

.upload-text {
  color: #8c939d;
  font-size: 14px;
}

.upload-tip {
  margin-top: 8px;
  color: #909399;
  font-size: 12px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 抽屉内容样式 */
.drawer-content {
  padding: 20px 0;
}

.drawer-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.upload-area-small {
  width: 200px;
  height: 150px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
    display: flex;
    align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
}

.upload-area-small:hover {
  border-color: #409EFF;
  background: #f5f7fa;
}

/* 表格样式优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  z-index: 1; /* 降低整个表格的z-index */
}

/* 确保表格固定列的 z-index 低于图片预览 */
:deep(.el-table__fixed),
:deep(.el-table__fixed-right),
:deep(.el-table__fixed-left),
:deep(.el-table__fixed-header-wrapper),
:deep(.el-table__fixed-body-wrapper),
:deep(.el-table__fixed-footer-wrapper) {
  z-index: 50 !important; /* 大幅降低，确保低于预览 */
}

:deep(.el-table__header) {
  background: #f5f7fa;
}

:deep(.el-table__header th) {
  background: #f5f7fa !important;
  border-bottom: 2px solid #e4e7ed;
  padding: 16px 0;
}

:deep(.el-table__body tr:hover > td) {
  background-color: #f5f7fa !important;
}

:deep(.el-table__body td) {
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-table__row) {
  transition: all 0.3s;
}

:deep(.el-table__row:hover) {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

/* 操作按钮组样式 */
:deep(.el-table__body .cell) {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: center;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>

<!-- 全局样式：修复图片预览被表格覆盖的问题 -->
<style>
/* 确保图片预览组件显示在最上层 - 使用更高优先级的选择器 */
body .el-image-viewer__wrapper,
.el-image-viewer__wrapper {
  z-index: 20000 !important;
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
}

body .el-image-viewer__mask,
.el-image-viewer__mask {
  z-index: 19999 !important;
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 100% !important;
  height: 100% !important;
  background: rgba(0, 0, 0, 0.8) !important;
}

body .el-image-viewer__canvas,
.el-image-viewer__canvas {
  z-index: 20000 !important;
  position: relative !important;
}

body .el-image-viewer__actions,
.el-image-viewer__actions {
  z-index: 20001 !important;
  position: relative !important;
}

body .el-image-viewer__close,
.el-image-viewer__close {
  z-index: 20002 !important;
  position: relative !important;
}

body .el-image-viewer__btn,
.el-image-viewer__btn {
  z-index: 20001 !important;
}

/* 预览对话框样式 */
.preview-container {
  background: #1a1a1a;
  border-radius: 8px;
  overflow: hidden;
  padding: 20px;
}

.preview-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 60vh;
}

.preview-image-full {
  max-width: 100%;
  max-height: 80vh;
  object-fit: contain;
  border-radius: 8px;
}
</style>